//
//  LNControllerHelper.m
//  WeiMa
//
//  Created by wwww on 2018/9/7.
//  Copyright © 2018年 淘发现1iOS. All rights reserved.
//

#import "LNControllerHelper.h"
#import "LNMainController.h"

@implementation LNControllerHelper
+ (UIViewController *)currentViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    
    /// CoderMikeHe Fixed : 这里必须要判断一下，否则取出来永远都是 MHHomePageViewController。这是架构上小缺(特)陷(性)。因为MHHomePageViewController的子控制器是UITabBarController，所以需要递归UITabBarController的所有的子控制器
    if ([resultVC isKindOfClass:[LNMainController class]]) {
        LNMainController *mainVc = (LNMainController *)resultVC;
        resultVC = [self _topViewController:mainVc.tabBarController];
    }
    
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

+ (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
}


+ (UINavigationController *)topNavigationController{
    return LNSharedAppDelegate.navigationControllerStack.topNavigationController;
}

+ (LNViewController *)topViewController
{
    LNViewController *topViewController = (LNViewController *)[self topNavigationController].topViewController;
    
    /// 确保解析出来的类 也是 MHViewController
    NSAssert([topViewController isKindOfClass:LNViewController.class], @"topViewController is not an MHViewController's subclass: %@", topViewController);
    
    return topViewController;
}

@end
